// Copyright 2010 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Author: tu@tulrich.com (Thatcher Ulrich)

// Generic JS utilities.

function el(id) {
  return document.getElementById(id);
}

function html_escape(msg) {
  return msg.replace(/&/g, '&amp;').
    replace(/>/g, '&gt;').
    replace(/</g, '&lt;').
    replace(/\"/g, '&quot;');
}

function lerp(x0, x1, t) {
  return (x1 - x0) * t + x0;
}

function clamp(x, xmin, xmax) {
  if (x < xmin) {
    return xmin;
  } else if (x > xmax) {
    return xmax;
  }
  return x;
}

function array_dedupe(a) {
  var found = {};
  var result = [];
  for (var i = 0; i < a.length; i++) {
    var val = a[i];
    if (!found[val]) {
      found[val] = true;
      result.push(val);
    }
  }
  return result;
}

function array_contains(a, value) {
  for (var i = 0; i < a.length; i++) {
    if (a[i] == value) {
      return true;
    }
  }
  return false;
}

function array_copy(a) {
  var result = [];
  for (var i = 0; i < a.length; i++) {
    result.push(a[i]);
  }
  return result;
}

// call func(k, v) for every element of container, and return the collected results.
function map(container, func) {
  var result = [];
  for (var k in container) {
    result.push(func(k, container[k]));
  }
  return result;
}

// Log to debug console, if possible.
function log() {
  if (console) {
    console.log.apply(console, arguments);
  }
}
